package org.example.warehouse.service.impl;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

import cn.hutool.json.JSONUtil;
import com.ruoyi.common.annotation.DataScope;
import com.ruoyi.common.core.domain.BaseEntity;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.ShiroUtils;
import org.example.contract.domain.ContractProduct;
import org.example.contract.mapper.ContractProductMapper;
import org.example.utils.Util;
import org.example.warehouse.domain.OrderDetail;
import org.example.warehouse.domain.WarehouseStore;
import org.example.warehouse.mapper.OrderDetailMapper;
import org.example.warehouse.mapper.WarehouseStoreMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.example.warehouse.mapper.MallStoreDetailMapper;
import org.example.warehouse.domain.MallStoreDetail;
import org.example.warehouse.service.IMallStoreDetailService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;

/**
 * 仓库存储详情Service业务层处理
 *
 * @author 小孟微信：xiaomengcode
 * @date 2024-04-12
 */
@Service
public class MallStoreDetailServiceImpl implements IMallStoreDetailService
{
    @Autowired
    private MallStoreDetailMapper mallStoreDetailMapper;
    @Autowired
    private WarehouseStoreMapper warehouseStoreMapper;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private ContractProductMapper contractProductMapper;

    /**
     * 查询仓库存储详情
     *
     * @param storeDetailId 仓库存储详情主键
     * @return 仓库存储详情
     */
    @Override
    public MallStoreDetail selectMallStoreDetailByStoreDetailId(Long storeDetailId)
    {
        return mallStoreDetailMapper.selectMallStoreDetailByStoreDetailId(storeDetailId);
    }

    /**
     * 查询仓库存储详情列表
     *
     * @param mallStoreDetail 仓库存储详情
     * @return 仓库存储详情
     */
    @Override
    @DataScope(deptAlias = "d", userAlias = "u")
    public List<MallStoreDetail> selectMallStoreDetailList(MallStoreDetail mallStoreDetail)
    {
        Util.setQuerySelfData((BaseEntity) mallStoreDetail);
        return mallStoreDetailMapper.selectMallStoreDetailList(mallStoreDetail);
    }

    /**
     * 新增仓库存储详情
     *
     * @param mallStoreDetail 仓库存储详情
     * @return 结果
     */
    @Override
    @Transactional
    public int insertMallStoreDetail(MallStoreDetail mallStoreDetail)
    {
        mallStoreDetail.setCreateTime(DateUtils.getNowDate());
        long total =Long.parseLong(mallStoreDetail.getParams().get ("code").toString());

        if(mallStoreDetail.getParams().containsKey("list")){
            String  list = mallStoreDetail.getParams().get("list").toString();
            List<ContractProduct> contractProducts = JSONUtil.parseArray(list).toList(ContractProduct.class);
            Date curDate=DateUtils.getNowDate();

            for(ContractProduct contractProduct:contractProducts){
                //1、更新合同产品清单
                contractProduct.setUseNum(contractProduct.getOperationNum()+handNullValue(contractProduct.getUseNum()));
                contractProduct.setRemainNum(handNullValue(contractProduct.getRemainNum())-contractProduct.getOperationNum());
                contractProduct.setCreateBy(ShiroUtils.getUserId()+"");
                contractProductMapper.updateContractProduct(contractProduct);

                //2、库存
                editWarehouseStore(contractProduct, curDate);

                //3、增加入库详情记录
                String storeDetailNo =  "GR"+DateUtils.dateTimeNow("yyMMdd")+String.format("%04d", total++);
                insertMallStoreDetail(contractProduct, storeDetailNo, curDate);
            }
            return contractProducts.size();
        }else{
            String storeDetailNo =  "GR"+DateUtils.dateTimeNow("yyMMdd")+String.format("%04d",  total+1);
            mallStoreDetail.setStoreDetailNo(storeDetailNo);
            mallStoreDetail.setCreateBy(ShiroUtils.getUserId()+"");
            mallStoreDetail.setCreateTime(DateUtils.getNowDate());
            mallStoreDetail.setOperationNum(mallStoreDetail.getNum());
            //更新库存
            editWarehouseStore(mallStoreDetail,mallStoreDetail.getCreateTime());
            //增加记录
            return mallStoreDetailMapper.insertMallStoreDetail(mallStoreDetail);
        }

    }

    private void insertMallStoreDetail(ContractProduct contractProduct, String storeDetailNo, Date curDate) {
        MallStoreDetail storeDetail =new MallStoreDetail();
        storeDetail.setStoreDetailNo(storeDetailNo);
        storeDetail.setContractId(contractProduct.getContractId());
        storeDetail.setOrderDetailId(contractProduct.getContractProductId());
        storeDetail.setWarehouseId(1L);
        storeDetail.setProductId(contractProduct.getProductId());
        storeDetail.setNum(contractProduct.getOperationNum());
        storeDetail.setPrice(contractProduct.getPrice());
        storeDetail.setCreateBy(ShiroUtils.getUserId()+"");
        storeDetail.setCreateTime(curDate);
        storeDetail.setRemark(contractProduct.getRemark());
        storeDetail.setSupplierId(contractProduct.getSupplierId());
        mallStoreDetailMapper.insertMallStoreDetail(storeDetail);
    }

    private void editWarehouseStore(ContractProduct contractProduct, Date curDate) {
        WarehouseStore store=new WarehouseStore();
        store.setProductId(contractProduct.getProductId());
        store.setWarehouseId(1L);
        store.getParams().put("deptId",ShiroUtils.getSysUser().getDeptId());
        WarehouseStore houseStoreDB= warehouseStoreMapper.selectMallWarehouseStoreByProductId(store);
        if(houseStoreDB !=null && houseStoreDB.getWarehouseStoreId()>0){
            //更新库存
            BigDecimal dbSumMoney=houseStoreDB.getAverageMoney().multiply(BigDecimal.valueOf(houseStoreDB.getRemainNum()));
            BigDecimal operationSumMoney =contractProduct.getPrice().multiply(BigDecimal.valueOf(contractProduct.getOperationNum()));
            BigDecimal sumMoney =dbSumMoney.add(operationSumMoney);
            Integer sumNum =houseStoreDB.getRemainNum()+contractProduct.getOperationNum();
            BigDecimal averageMoney =sumMoney.divide(BigDecimal.valueOf(sumNum),2,BigDecimal.ROUND_HALF_UP);
            houseStoreDB.setAverageMoney(averageMoney);//平均价

            houseStoreDB.setNum(houseStoreDB.getNum()+ contractProduct.getOperationNum());
            houseStoreDB.setRemainNum(handNullValue(houseStoreDB.getRemainNum())+ contractProduct.getOperationNum());
            warehouseStoreMapper.updateWarehouseStore(houseStoreDB);
        }else{
            //新增库存
            store.setNum(contractProduct.getOperationNum());
            store.setRemainNum(contractProduct.getOperationNum());
            store.setWarehouseId(1L);
            store.setCreateBy(ShiroUtils.getUserId()+"");
            store.setCreateTime(curDate);
            store.setCheckNum(contractProduct.getOperationNum());
            store.setAverageMoney(contractProduct.getPrice());
            warehouseStoreMapper.insertWarehouseStore(store);
        }
    }


    private Integer handNullValue(Integer value){

        if(value==null){
            return 0;
        }
        return value;
    }
    /**
     * 修改仓库存储详情
     *
     * @param mallStoreDetail 仓库存储详情
     * @return 结果
     */
    @Override
    public int updateMallStoreDetail(MallStoreDetail mallStoreDetail)
    {
        return mallStoreDetailMapper.updateMallStoreDetail(mallStoreDetail);
    }

    /**
     * 批量删除仓库存储详情
     *
     * @param storeDetailIds 需要删除的仓库存储详情主键
     * @return 结果
     */
    @Override
    public int deleteMallStoreDetailByStoreDetailIds(String storeDetailIds)
    {
        return mallStoreDetailMapper.deleteMallStoreDetailByStoreDetailIds(Convert.toStrArray(storeDetailIds));
    }

    /**
     * 删除仓库存储详情信息
     *
     * @param storeDetailId 仓库存储详情主键
     * @return 结果
     */
    @Override
    public int deleteMallStoreDetailByStoreDetailId(Long storeDetailId)
    {
        return mallStoreDetailMapper.deleteMallStoreDetailByStoreDetailId(storeDetailId);
    }
}
